package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping_back.common.Result;
import com.shopping_back.mapper.MemberOrderMapper;
import com.shopping_back.pojo.entity.MemberOrder;
import com.shopping_back.pojo.entity.UserProfile;
import com.shopping_back.service.MemberService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl extends ServiceImpl<MemberOrderMapper, MemberOrder> implements MemberService {
    @Autowired
    private MemberOrderMapper memberOrderMapper;

    @Autowired
    private  UserProfileServiceImpl userProfileService;

    @Autowired
    private JwtUtils jwtUtils;

    private static final Map<Integer, Integer> LEVEL_BASE_PRICE_MAP = new HashMap<>();
    static {
        // 和前端 calculateRenewFee 的 basePrice 保持一致
        LEVEL_BASE_PRICE_MAP.put(1, 0);
        LEVEL_BASE_PRICE_MAP.put(2, 10);
        LEVEL_BASE_PRICE_MAP.put(3, 20);
        LEVEL_BASE_PRICE_MAP.put(4, 30);
        LEVEL_BASE_PRICE_MAP.put(5, 50);
    }

    @Override
    public Map<String, String> getMemberValidity(HttpServletRequest request) {
        Long userId = jwtUtils.getCurrentUserId(request);
        MemberOrder order = memberOrderMapper.selectLatestOrder(userId);
        UserProfile user = userProfileService.getById(userId);

        // 返回统一数据结构
        Map<String, String> result = new HashMap<>();

        if (user.getMembershipLevel() == 1) {
            result.put("level", "银米会员");
            result.put("start_date", user.getCreateTime().toLocalDate().toString()); // 使用注册时间
            result.put("end_date", "无");
            return result;
        }


        result.put("start_date", order != null ? order.getStartDate().toString() : "无");
        result.put("end_date", order != null ? order.getEndDate().toString() : "无");
        return result;
    }

    @Override
    public List<Integer> getAvailableLevels(Long userId) {
        Integer currentLevel = userProfileService.getById(userId).getMembershipLevel();
        return IntStream.rangeClosed(2, 5)
                .filter(level -> level > currentLevel)
                .boxed()
                .collect(Collectors.toList());
    }

    @Override
    public Result upgradeMember(Long userId, Integer targetLevel, Integer months) {
        // 1. 验证等级有效性
        if (!getAvailableLevels(userId).contains(targetLevel)) {
            return Result.error("非法的升级等级");
        }
        Integer basePrice = LEVEL_BASE_PRICE_MAP.getOrDefault(targetLevel, 0);
        BigDecimal amount = new BigDecimal(basePrice * months);

        // 2. 创建新订单（匹配图片中的member_orders结构）
        MemberOrder order = new MemberOrder();
        order.setUserId(userId);
        order.setLevel(targetLevel);
        order.setStartDate(LocalDate.now());
        order.setEndDate(LocalDate.now().plusMonths(months));
        order.setAmount(amount);
        order.setStatus(1);
        save(order);

        // 3. 更新用户等级
        userProfileService.lambdaUpdate()
                .eq(UserProfile::getUserId, userId)
                .set(UserProfile::getMembershipLevel, targetLevel)
                .update();

        return Result.success("升级成功");
    }

    @Override
    public Result renewMember(Long orderId, Integer months) {
        MemberOrder order = getById(orderId);
        if (order == null || order.getStatus() != 1) {
            return Result.error("无效的会员订单");
        }

        // 延长有效期（图片中的end_date字段）
        order.setEndDate(order.getEndDate().plusMonths(months));
        updateById(order);

        return Result.success("续费成功");
    }

    /**
     * 执行自动降级（完全基于图片中的代码逻辑）
     * @param userId 要降级的用户ID
     * @return 是否执行了降级
     */
    @Override
    public boolean executeAutoDowngrade(Long userId) {
        MemberOrder order = memberOrderMapper.selectLatestOrder(userId);

        // 图片中的核心逻辑 ▼
        if (order != null && order.getEndDate().isBefore(LocalDate.now())) {
            userProfileService.lambdaUpdate()
                    .eq(UserProfile::getUserId, userId)
                    .set(UserProfile::getMembershipLevel, 1)
                    .update();

            order.setStatus(0); // 标记订单过期
            memberOrderMapper.updateById(order);
            return true;
        }
        return false;
    }

    @Override
    public BigDecimal getMemberDiscount(Long userId) {
        // 1. 查询用户会员等级
        UserProfile user = userProfileService.getByUserId(userId);

        switch (user.getMembershipLevel()) {
            case 1:
                return BigDecimal.ONE;  // 5% off
            case 2:
                return BigDecimal.valueOf(0.95);  // 10% off
            case 3:
                return BigDecimal.valueOf(0.90);  // 15% off
            case 4:
                return BigDecimal.valueOf(0.85);  // 20% off
            default:  // REGULAR或其他
                return  BigDecimal.valueOf(0.80);// 0% off
        }
    }

}